#!/usr/bin/env python

import os
import subprocess
import utility


class Flowtool:
    def __init__(self, capreader_path):
        self.__setup__()
        self.u = utility.Utility()
        self.capreader_path = capreader_path

    def __setup__(self):
        self.flowtool_path = "/root/flowtool/flowtool"
        self.config_path = "/root/flowtool/flowtool_config.txt"
        self.config_path_40 = "/root/flowtool/flowtool_config_40.txt"

    def run_command(self, cmd):
        """ Runs command 'cmd' in linux terminal """
        subprocess.call(cmd, shell=True)

    def run_flowtool(self, file_path):
        """ Runs flowtool on all file specified in file_path """
        if os.path.isfile(file_path):
            try:
                cmd = self.flowtool_path
                cmd += " -o " + self.config_path
                cmd += " -D " + self.capreader_path
                cmd += " -V " + file_path
                self.run_command(cmd)
            except Exception, error_msg:
                print error_msg
        else:
            print "Invald file: %s" % file_path
            
    def run_flowtool_redirect(self, file_path, output_dir):
        """ ***This only works with NAVL 4.0***
            Allows you to redirect the flowtool
            log files to the path of your choice """
        if os.path.isfile(file_path):
            try:
                cmd = self.flowtool_path
                cmd += " -o " + self.config_path_40
                cmd += " -D " + self.capreader_path
                cmd += " -V " + file_path
                cmd += " -O " + output_dir
                self.run_command(cmd)
            except Exception, error_msg:
                print error_msg
        else:
            print "Invald file: %s" % file_path

    def run_flowtool_folder(self, directory):
        """ Runs flowtool on all files in 'directory' """
        if os.path.isdir(directory):
            files = utility.Directory(directory, ".pcap")
            print "Total number of files is: %s" % str(files.count())
            for f in files:
                print f + "\t" + files.percentage(f)
                self.run_flowtool(f)
        else:
            print "Invalid directory: %s" % str(directory)